﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using System.IO;

namespace HTMLConvExample
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void bnConvert_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string sSource = MapPath(@"temp/") + FileUpload1.FileName;
                Directory.CreateDirectory(MapPath(@"temp/"));
                FileUpload1.SaveAs(sSource);
                Label1.Text = "File Uploaded: " + FileUpload1.FileName;

                Type oType = Type.GetTypeFromProgID("HTMLConverter.HTMLConverterX");
                if (oType == null)
                {
                    Response.Redirect("RegSvr.aspx");
                    return;
                }

                
                // We use late bindings to allow build without installed HTMLConverterX
                // You should use syntax like:
                //IHTMLConverterX Conv = (IHTMLConverterX)Activator.CreateInstance(oType);
                // with HTMLConverter reference

                object Conv = Activator.CreateInstance(oType);
                
                string sFormat = rblConvert.SelectedValue;
                string sConverted = Path.ChangeExtension(sSource, "." + sFormat);
                string sCmd = "-c " + sFormat + " " + edAdditional.Text;

                object[] parameters;
                parameters = new object[3];
                parameters[0] = sSource;
                parameters[1] = sConverted;
                parameters[2] = sCmd;

                Conv.GetType().InvokeMember("Convert", BindingFlags.InvokeMethod, null, Conv, parameters);
                /*Conv.Convert(
                    sSource, 
                    sConverted,
                    sCmd); */

                Global.cmd = sCmd;
                Global.destination = sConverted;
                Response.Redirect("Converted.aspx");
                
            }
            else
            {
                Label1.Text = "No File Uploaded.";
            }

        }
    }
}